$(document).on("submit","form.ajax",function(e) {
  $.ajax({
      type: $(this).attr("method"),
      url: $(this).attr("action"),
      data: $(this).serialize(),
      success: function(msg) {
          // console.log(msg);
          /**
           * 返回数据格式为json 包含以下字段 msg（提示信息） code（错误代码 默认0错误 1成功）
           * isreload（是否刷新）url（成功后跳转） errorurl（失败后跳转）
           */
          if (msg.code == '0' || msg.code == 0) {
              if (msg.ask !== undefined && msg.ask != "") {
                  layer.confirm(msg.ask, {
                      btn: ['继续', '返回'],
                      closeBtn: 0,
                      title: '询问',
                  }, function() {
                      window.setTimeout("window.location.reload();", 100);
                  }, function() {
                      window.setTimeout("window.history.go(-1);", 100);
                  });
              } else {
                  layer.msg(msg.msg, {
                      icon: 6,
                  });
              }
          } else {
              layer.alert(msg.msg, {
                  icon: 5,
                  title: '提示',
              });
          }

          if (msg.url !== undefined && msg.url != "") {
              window.setTimeout("window.location = '" + msg.url + "';", 600);
          }
          if (msg.back >= '1') {
              window.setTimeout("window.history.go(-" + msg.back + ");", 600);
          }
          if (msg.isreload == '1') {
              window.setTimeout("window.location.reload();", 600);
          }
      },
      error: function(error) {
          layer.msg("网络错误");
      }
  })
  return false
})
$(document).on("click","[action='panel']",function(){
    var url = $(this).attr("action-url");
    var title = $(this).attr("action-title");
    var area = $(this).attr("action-area");
    var call = $(this).attr("action-callback");
    var after = $(this).attr("action-after");
    if(!title) {
        title = ''
    }
    if(!area) {
        area = "800px";
    }
    var data = {}
    if(call) {
        var d = eval(call)
        if(!d) {
            return;
        }else {
            data = d
        }
    }
    data.no_json = true
    $.ajax({
        type:'get',
        url:url,
        data:data,
        success:function(res){
            var p = new panel({
                width:area,
                title:title,
                html:res
            })
            var laydate = layui.laydate;
            $(".layui-date").each(function(){
                laydate.render({
                    elem:this,
                    type:"date"
                });

            });
            var form = layui.form;
            form.render();
            if(after){
                (new Function("p","return " + after + "(p)"))(p)
            }
            var element = layui.element;
            element.render()

        },
        error:function(data){
            layui.use('layer',function(){
                var layer = layui.layer;
                layer.open({
                    type:4,
                    content:"服务器信息错误",
                    title:"提示",
                    area: '300px'
                });
            });
        }
    })
})
$(document).on("click", "[action='dialog']",function(){
    var url = $(this).attr("action-url");
    var title = $(this).attr("action-title");
    var area = $(this).attr("action-area");
    var call = $(this).attr("action-callback");
    var after = $(this).attr("action-after");
    var data = {};
    if(!title){
        title = '';
    }
    if(!area){
        area = "800px";
    }

    if(call){
        var d = eval(call);
        if(!d){
            return;
        }else{
            data = d;
        }
    }
    data.no_json = true
    $.ajax({
        method:'get',
        url:url,
        data:data,
        success:function(data){
            layui.use(['layer','form','laydate'], function(){
                pop_form = layui.layer;
                pop_form.open({
                    type:1,
                    content:data,
                    title:title,
                    area:area,
                    success:function(){
                        var laydate = layui.laydate;
                        $(".layui-date").each(function(){
                            laydate.render({
                                elem:this,
                                type:"date"
                            });

                        });
                        var form = layui.form;
                        form.render();
                        if(after){
                            eval(after+"(data)");
                        }
                    }

                });


            });
        },
        error:function(data){
            layui.use('layer',function(){
                var layer = layui.layer;
                layer.open({
                    type:4,
                    content:"服务器信息错误",
                    title:"提示",
                    area: '300px'
                });
            });
        }
    })
})
$(document).on("click", "[action='ajax']",function(){
    var msg = $(this).attr("action-ask");
    if(msg && msg != "") {
        var r = confirm(msg);
        if(!r){
            return;
        }
    }

    var url = $(this).attr("action-url");
    $.ajax({
        type:"get",
        url:url,
        success: function (msg) {
            if (msg.code == '0' || msg.code == 0) {
                if (msg.ask !== undefined && msg.ask != "") {
                    layer.confirm(msg.ask, {
                        btn: ['继续', '返回'],
                        closeBtn: 0,
                        title: '询问',
                    }, function () {
                        window.setTimeout("window.location.reload();", 100);
                    }, function () {
                        window.setTimeout("window.history.go(-1);", 100);
                    });
                } else {
                    layer.msg(msg.msg, {
                        icon: 6,
                    });
                    layer.close();
                }
                window.setTimeout("window.location.reload();", 100);
            } else {
                layer.alert(msg.msg, {
                    icon: 5,
                    title: '提示',
                });
            }

            if (msg.url !== undefined && msg.url != "") {
                window.setTimeout("window.location = '" + msg.url + "';", 600);
            }
            if (msg.back >= '1') {
                window.setTimeout("window.history.go(-" + msg.back + ");", 600);
            }
            if (msg.isreload == '1') {
                window.setTimeout("window.location.reload();", 600);
            }
        },
        error: function (error) {
            layer.msg("网络错误");
        }
    })
})
$(document).on("click", "[action='del']",function () {
    var r = confirm("确认删除吗？");
    if(!r){
        return;
    }
    var url = $(this).attr("action-url");
    $.ajax({
        type:"get",
        url:url,
        success: function (msg) {
            if (msg.code == '0' || msg.code == 0) {
                if (msg.ask !== undefined && msg.ask != "") {
                    layer.confirm(msg.ask, {
                        btn: ['继续', '返回'],
                        closeBtn: 0,
                        title: '询问',
                    }, function () {
                        window.setTimeout("window.location.reload();", 100);
                    }, function () {
                        window.setTimeout("window.history.go(-1);", 100);
                    });
                } else {
                    layer.msg(msg.msg, {
                        icon: 6,
                    });
                    layer.close();
                }
                window.setTimeout("window.location.reload();", 100);
            } else {
                layer.alert(msg.msg, {
                    icon: 5,
                    title: '提示',
                });
            }

            if (msg.url !== undefined && msg.url != "") {
                window.setTimeout("window.location = '" + msg.url + "';", 600);
            }
            if (msg.back >= '1') {
                window.setTimeout("window.history.go(-" + msg.back + ");", 600);
            }
            if (msg.isreload == '1') {
                window.setTimeout("window.location.reload();", 600);
            }
        },
        error: function (error) {
            layer.msg("网络错误");
        }
    })
})
$(document).on("click", "[action='upload']",function () {
    var files = $(this).attr("action-data");
    var callback = $(this).attr("action-event");
    var that = this;
    $.ajax({
        type:'get',
        url:"{:url('file/_form')}",
        data:{files:files},
        success:function (data) {
            layui.use(['layer'], function(){
                file_layer = layui.layer;
                file_layer.open({
                    type:1,
                    content:data,
                    title:"图片上传",
                    area:"500px",
                    btn:['确定','取消'],
                    yes:function(index,layero){
                        var filepath = $("#upload_path").val();
                        eval(callback+"(that,filepath)");
                        layer.close(index);
                    },
                    no:function(index,layero){
                    }
                });
            });
        }
    })
})
$(document).on("click","[action='scan']",function(){
    var ctrl_token = $(this).attr("action-token");
    var seed = $(this).attr("action-seed");
    var that = this;
    $.ajax({
        type:'get',
        url:"{:url('scan/index')}",
        data:{"seed":seed},
        success:function(data){
            layui.use(['layer'],function(){
                var layer = layui.layer;
                layer.open({
                    type:1,
                    content:data.data.content,
                    title:"扫码上传",
                    area:"500px",
                    btn:['确定','取消'],
                    yes:function(index,layero){
                        console.log("yes");
                        $.ajax({
                            type:'get',
                            url:"{:url('scan/path')}",
                            data:{"token":data.data.bar_code},
                            success:function(data){
                                if(data.code == 0){
                                    var img_container = $(that).next();
                                    if(img_container.length == 0){
                                        img_container = $("<div style = 'display: inline-block;'></div>");
                                        $(that).parent().append(img_container);
                                    }
                                    img_container.children().remove();
                                    var imgArr = data.data.pathes.split(";");
                                    for(var i = 0 ;i < imgArr.length;i++){
                                        var img = imgArr[i];
                                        img_container.append("<img src = '" + img + "'/>");
                                    }
                                    $("#" + ctrl_token).val(data.data.pathes);
                                }else{
                                    alert("未取得上传文件")
                                }
                            }
                        });
                        layer.close(index);
                    },
                    no:function(index,layero){

                    }

                });
            });
        }
    });
});